﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Linq;

namespace NB_Controller_Test
{
    public class SendCmds
    {
        public class SendCmd
        {
            public string strName;
            
            public string strProl_ID;
            public string strProl_Ver;
            public string strIsRsp;
            public string strContentType;

            public string strDatas;

            public SendCmd()
            {

            }

            public SendCmd(SendCmd other)
            {
                strName = other.strName;

                strProl_ID = other.strProl_ID;
                strProl_Ver = other.strProl_Ver;
                strIsRsp = other.strIsRsp;
                strContentType = other.strContentType;

                strDatas = other.strDatas;
            }
        }
        //名字不能有空格
        protected const string XML_NODE_PROJECT = "Project";

        //发送命令相关定义
        protected const string XML_SENDCMDS = "SendCmds";
        protected const string XML_NAME = "Name";
        protected const string XML_Prol_ID = "Prol_ID";
        protected const string XML_Prol_Ver = "Prol_Ver";
        protected const string XML_IsRsp = "IsRsp";
        protected const string XML_ContentType = "ContentType";
        protected const string XML_DATAS = "Datas";

        public string PathName;

        //要实现可拖动、排序可考虑：
        //1、记忆位置，在Canvas中设定并允许拖动
        //2、利用Thembr，但如何解决内容显示
        public List<SendCmd> sendCmdArry = new List<SendCmd>();
        //public UInt16 uiSendCmdCount = 0;

        public SendCmds()
	    {
            PathName = System.Windows.Forms.Application.StartupPath + "\\SendCmdConfig.xml";
            Open();
        }

        public bool Open()
        {
            bool bRet = true;

            try
            {
                XmlDocument _xmldoc = new XmlDocument();
                _xmldoc.Load(PathName);

                XmlNode nodePage = _xmldoc.SelectSingleNode(XML_NODE_PROJECT);
                if (nodePage != null)
                {
                    foreach (XmlNode _node in nodePage.ChildNodes)
                    {
                        if (_node.NodeType != XmlNodeType.Element) 
                            continue;

                        XmlElement _elm = (XmlElement)_node;                        

                        //================================
                        if (_elm.Name.Equals(XML_SENDCMDS))
                        {
                            ParseXMLSendCmds(_elm);
                        }
                    }
                }
            }
            catch 
            {                
                //Save();
            }
            return bRet;
        }

        public bool Save()
        {
            //删除前先备份，以防万一
            string strPathNameBack = System.Windows.Forms.Application.StartupPath + "\\SendCmdConfigAutoBack.xml";
            if (File.Exists(PathName))
            {
                File.Delete(strPathNameBack);
                File.Move(PathName, strPathNameBack);
            }

            XDocument xDoc = new XDocument();
            XElement xRoot = new XElement(XML_NODE_PROJECT);
            // 添加节点使用Add
            xDoc.Add(xRoot);

            for (int i = 0; i < sendCmdArry.Count; i++)
            {
                SendCmd sendCmd = sendCmdArry[i];

                XElement xSendCmdsItem = new XElement(XML_SENDCMDS);
                xRoot.Add(xSendCmdsItem);

                XElement xDevNameItem = new XElement(XML_NAME);
                xDevNameItem.Value = sendCmd.strName;
                xSendCmdsItem.Add(xDevNameItem);

                XElement xDevProlIDItem = new XElement(XML_Prol_ID);
                xDevProlIDItem.Value = sendCmd.strProl_ID;
                xSendCmdsItem.Add(xDevProlIDItem);

                XElement xDevProlVerItem = new XElement(XML_Prol_Ver);
                xDevProlVerItem.Value = sendCmd.strProl_Ver;
                xSendCmdsItem.Add(xDevProlVerItem);        
        
                XElement xDevIsRspItem = new XElement(XML_IsRsp);
                xDevIsRspItem.Value = sendCmd.strIsRsp;
                xSendCmdsItem.Add(xDevIsRspItem); 

                XElement xDevContentTypeItem = new XElement(XML_ContentType);
                xDevContentTypeItem.Value = sendCmd.strContentType;
                xSendCmdsItem.Add(xDevContentTypeItem); 

                XElement xDevDATASItem = new XElement(XML_DATAS);
                xDevDATASItem.Value = sendCmd.strDatas;
                xSendCmdsItem.Add(xDevDATASItem); 
            }
            
            //保存该文档  
            xDoc.Save(PathName);

            return true;
        }

        public bool AddNewCmd(SendCmd sendCmd)
        {
            //if (uiSendCmdCount >= 100/*Marshal.SizeOf(sendCmdArry)*/)
            //    return false;
            //else
            //    sendCmdArry[uiSendCmdCount++] = sendCmd;

            //添加以前检测一下是否已经存在，若存在不允许添加
            SendCmd sendCmdFind = FindSendCmdByName(sendCmd.strName);
            if(sendCmdFind == null)
            {
                sendCmdArry.Add(sendCmd);
                return true;
            }                
            else
            {
                System.Diagnostics.Debug.WriteLine(sendCmd.strName + " 命令已存在，不能添加");
                return false;
            }
        }

        public bool RemoveCmd(string strName)
        {
            for (int i = 0; i < sendCmdArry.Count; i++)
            {
                SendCmd sendCmd = sendCmdArry[i];
                if(sendCmd.strName == strName)
                {
                    sendCmdArry.Remove(sendCmd);
                    return true;
                }
            }

            return false;
        }

        ///*******************************************************************************
        /// <summary>
        /// 解析 近端秘钥列表
        /// </summary>
        /// <param name="_elm"></param>
        ///*******************************************************************************
        public void ParseXMLSendCmds(XmlElement _elm)
        {
            if (_elm.Name.Equals(XML_SENDCMDS))
            {
                SendCmd sendCmd = new SendCmd();

                foreach (XmlNode xmlNode in _elm.ChildNodes)
                {
                    if (xmlNode.NodeType != XmlNodeType.Element) 
                        continue;
                    XmlElement xmlElm = (XmlElement)xmlNode;
                   
                    if (xmlElm.Name.Equals(XML_NAME))
                    {
                        sendCmd.strName = xmlElm.InnerText;                                              
                    }
                    else if (xmlElm.Name.Equals(XML_Prol_ID))
                    {
                        sendCmd.strProl_ID = xmlElm.InnerText;
                    }
                    else if (xmlElm.Name.Equals(XML_Prol_Ver))
                    {
                        sendCmd.strProl_Ver = xmlElm.InnerText;
                    }
                    else if (xmlElm.Name.Equals(XML_IsRsp))
                    {
                        sendCmd.strIsRsp = xmlElm.InnerText;
                    }
                    else if (xmlElm.Name.Equals(XML_ContentType))
                    {
                        sendCmd.strContentType = xmlElm.InnerText;
                    }
                    else if (xmlElm.Name.Equals(XML_DATAS))
                    {
                        sendCmd.strDatas = xmlElm.InnerText;
                    } 
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("xmlElm.Name " + xmlElm.Name + "尚未解析。");
                    }
                }

                //判断是否有重复数据
                //SendCmds.SendCmd sendCmdExist = FindSendCmdByName(sendCmd.strName);
                //if (sendCmd != null)
                //{
                //    //有重复
                //}
                //else
                //{
                //    //无重复
                //}

                //添加时自我判断
                AddNewCmd(sendCmd);
            }
        }        

        /// <summary>
        /// 根据名称查找发送的数据
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        private string FindSendDatasByName(string strName)
        {
            for (int i = 0; i < sendCmdArry.Count; i++)
            {
                SendCmds.SendCmd sendCmd = sendCmdArry[i];
                if(sendCmd.strName == strName)
                {
                    return sendCmd.strDatas;
                }
            }

            return "";
        }

        public SendCmds.SendCmd FindSendCmdByName(string strName)
        {
            for (int i = 0; i < sendCmdArry.Count; i++)
            {
                SendCmds.SendCmd sendCmd = sendCmdArry[i];
                if (sendCmd.strName == strName)
                {
                    return sendCmd;
                }
            }

            return null;
        }

        public void SortSendCmdsByNames(List<ButThumb> thumbList)
        {
            SendCmds sendCmds = new SendCmds();
            sendCmds.sendCmdArry.Clear();
            foreach (SendCmd sendCmd in sendCmdArry)
            {
                SendCmd sc = new SendCmd(sendCmd);
                sendCmds.AddNewCmd(sc);
            }

            //清空
            sendCmdArry.Clear();

            //thumbList根据Index排序
            //thumbList.Sort();
            thumbList.Sort
                (
                    delegate(ButThumb item1, ButThumb item2)
                    {
                        return item1.Index - item2.Index;
                    }
                );

            foreach(ButThumb butThumb in thumbList)
            {
                Button butCmd = (Button)butThumb.Template.FindName("Button", butThumb);

                SendCmd sc = sendCmds.FindSendCmdByName(butCmd.Content.ToString());
                sendCmdArry.Add(sc);
            }
        }
    }
}
